﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;

namespace Hisun.View.SCRB
{
    public partial class Scrb_Daily_PAUSE : System.Web.UI.Page
    {
        private string mypipID;
        int mycostcenterID;
        DateTime dt_myday;
        public string alter;

        HisunDBDataContext db = new HisunDBDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            mypipID = HttpUtility.UrlDecode(Request.QueryString["mypip"]);
            dt_myday = DateTime.Parse(HttpUtility.UrlDecode(Request.QueryString["myday"]));
            bindmypip();

            if (!IsPostBack)
            {

                BindEmptyData();
            }
        }

        /// <summary>
        /// 获取当前会计期间
        /// </summary>
        /// <param name="it_date"></param>
        /// <returns></returns>
        private string getAccoutperiod(DateTime it_date)
        {

            var kjqk = (from a in db.TABC_JS_AccountPeriod
                        where a.成本开始日期 <= it_date
                               && a.成本结账日期 >= it_date
                        select a.会计期间ID).Single();

            return kjqk;
        }
        private string getAccoutperiod()
        {
            return getAccoutperiod(this.dt_myday);
        }

        private void bindmypip()
        {
            var mypip = (from a in db.TABC_JS_ProductInProcess
                         where a.中间体ID == mypipID
                         select a).Single();


            mycostcenterID = (int)mypip.作业中心ID;
            string mycostcentername = (from a in db.TABC_JS_CostCenter
                                       where a.作业中心ID == mycostcenterID
                                       select a.作业中心名称).Single();

            Label_CostCenter.Text = mycostcentername;
            Label_PIPNAME.Text = mypip.中间体名称;
            Label_myday.Text = dt_myday.ToShortDateString();



        }

        private string splitbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                batch = batch.Split('/')[1];
            }

            return batch;
        }

        private string joinbatch(string batch)
        {
            if (batch.IndexOf('/') > 0)
            {
                return batch;
            }
            return this.mypipID + "/" + batch;

        }

        

        protected void BindEmptyData()
        {
            var qs = from a in db.TSCRB_JS_BatchInfo
                     join b in db.TSCRB_JS_BatchInfoDetail
                     on a.批号 equals b.批号
                     join c in db.TSCRB_DM_BatchStatus 
                     on a.批号类型 equals c.DM
                     where a.中间体ID == mypipID 
                     && (a.批号类型 == "N" || a.批号类型 == "C" || a.批号类型 == "R" || a.批号类型 == "P") 
                     && (b.中止日期 == null || b.中止日期 == dt_myday)
                     && b.投入日期 <=dt_myday
                     select new
                     {
                         b.ID,
                         a.批号,
                         status = (c.状态),
                         中止 = (a.批号类型 == "P"),
                         数量 = a.数量

                     };
            GridView1.DataSource = qs;
            GridView1.DataBind();
        }
        protected DataTable GetDataFromGrid()
        {

            DataTable dt1 = new DataTable();
            dt1.Columns.Add("ID");
            dt1.Columns.Add("批号");
            dt1.Columns.Add("中止");
            dt1.Columns.Add("数量");

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow gRow = GridView1.Rows[i];
                DataRow newRow = dt1.NewRow();
                newRow[0] = GridView1.DataKeys[i].Value;
                newRow[1] = ((TextBox)gRow.FindControl("TextBox1")).Text;
                newRow[2] = ((CheckBox)gRow.FindControl("CheckBox1")).Checked;
                newRow[3] = ((TextBox)gRow.FindControl("TextBox2")).Text;
                //newRow[3] = ((TextBox)gRow.FindControl("TextBox3")).Text;
                dt1.Rows.Add(newRow);
            }
            dt1.AcceptChanges();
            return dt1;
        }


        private bool checkbachexist(string batchnumber)
        {
            if (batchnumber.IndexOf('/') < 0)
            {
                batchnumber = joinbatch(batchnumber);
            }
            var q = from a in db.TSCRB_JS_BatchInfo
                    where
                        a.批号 == batchnumber
                    select a;
            if (q.Count() > 0)
            {
                return true;
            }
            return false;

        }
        protected void Button_Save_Click(object sender, EventArgs e)
        {
            DataTable dt1 = GetDataFromGrid(); 
            float 数量;
            try
            {
                foreach (DataRow row in dt1.Rows)
                {
                    if (row["ID"] != DBNull.Value)
                    {
                        if (row["批号"].ToString().Length > 1)
                        {

                            var updatedetail = (from a in db.TSCRB_JS_BatchInfoDetail
                                                where a.ID == long.Parse(row["ID"].ToString())
                                                select a).Single();
                            var update = (from a in db.TSCRB_JS_BatchInfo
                                          where a.批号 == updatedetail.批号
                                          select a).Single();
                            if (row["中止"].ToString() == "True")
                            {

                                数量 = 0;
                                float.TryParse(row["数量"].ToString(), out 数量);
                                update.批号类型 = "P";
                                updatedetail.中止日期 = dt_myday;
                                update.数量 = 数量;
                                update.结束日期 = dt_myday;
                                //update.状态=""
                            }
                            else
                            {
                                if (update.批号类型 == "P")
                                {
                                    update.批号类型 = "N";
                                    update.数量 = 0;
                                    update.结束日期 = null;
                                    updatedetail.中止日期 = null;
                                }

                            }


                            db.SubmitChanges();

                        }
                    }

                }

                alter = "<script>alert('保存成功！！');</script>";
            }
            catch
            {

                alter = "<script>alert('保存失败！！');</script>";
               
            }

 
            BindEmptyData();

        }

        protected void Button_Back_Click(object sender, EventArgs e)
        {
            Response.Redirect("Scrb_Daily_MainPage.aspx?centerid=" + mycostcenterID.ToString() + "&PIPid=" + mypipID);
      
        }
    }
}
